package cn.shenlong.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.shenlong.common.Constants;
import cn.shenlong.portal.domain.User;
import cn.shenlong.portal.service.UserService;

public class AdminInterceptor extends HandlerInterceptorAdapter {

	public static final String publickey = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKsZnA0ZPlzaUveP8aUYqy3jQkuF3cVsxlOkrbYlS22NPVwL1PHkrMYVlkrt04bxLhEXgHLDe+0kxzkRSEWdnRsCAwEAAQ==";
	private static Logger logger = LoggerFactory
			.getLogger(AdminInterceptor.class);

	@Autowired
	private UserService userService;

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {

		try {
			User user = (User) request.getSession().getAttribute("admin_user");
			List<User> result = userService.findUserByRegistName(user
					.getRegistName());
			if (result != null && result.size() == 1) {
				if (result.get(0).getPassword().trim()
						.equals(user.getPassword().trim())) {
					return true;
				} else {
					logger.info("登录异常！");
					request.getSession().invalidate();
					response.sendRedirect(Constants.ADMIN_LOGIN_URL);
					return false;
				}

			} else {
				logger.info("登录异常！");
				request.getSession().invalidate();
				response.sendRedirect(Constants.ADMIN_LOGIN_URL);
				return false;
			}
		} catch (Exception e) {

			request.getSession().invalidate();
			response.sendRedirect(Constants.ADMIN_LOGIN_URL);
			return false;

		}

	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}

}
